'use strict';

const { resolve } = require('path');
const Package = require('@ysx-cli/package');
const log = require('@ysx-cli/log');
const { smartSpawn } = require('@ysx-cli/utils');

// 命令映射
const SETTINGS = {
  create: '@ysx-cli/create'
}

const CACHE_DIR = 'dependencies';

async function exec(...args) {
  // 要执行的命令,eg: create
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;
  const cmdObj = args.pop();
  const cmdName = cmdObj.name(); // 命令名称: create
  const packageName = SETTINGS[cmdName];
  const packageVersion = 'latest';
  // const packageVersion = '1.1.0';

  let pkg;
  if (targetPath) {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion
    });
  } else {
    targetPath = resolve(homePath, CACHE_DIR);
    const storeDir = resolve(targetPath, 'node_modules');
    log.verbose('targetPath', targetPath);
    log.verbose('storeDir', storeDir);

    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion
    });
    if (await pkg.exists()) {
      await pkg.update();
    } else {
      await pkg.install();
    }
  }

  const entryFile = pkg.entryFilePath();
  // console.log('entryFile>>', entryFile); 真正要使用的命令比如：D:\codes\架构\ysx-cli\commands\create
  if (entryFile) {
    try {
      // 在当前的主进程调用
      // require(entryFile)(args.concat(cmdObj));
      // cmdObj暂时没用到不传，参考week4 6-4
      const code = `require('${entryFile}')(${JSON.stringify(args)});`;
      /*
      * node -e 可执行js code str
      * windows下：spawn('cmd', ['/c', 'node', '-e', code])
      * */
      const childProcess = smartSpawn('node', ['-e', code], {
        cwd: process.cwd(),
        stdio: 'inherit'
      });
      childProcess.on('error', (error) => {
        console.log('命令执行失败', error);
        process.exit(1); // 以错误的方式强制退出
      });

      childProcess.on('exit', code => {
        console.log('命令执行完毕');
        process.exit(code);
      });

    } catch (error) {
      log.error(error);
    }
  }
}

module.exports = exec;
